<?php
declare(strict_types=1);


namespace App\Common;


use Hyperf\HttpServer\Contract\RequestInterface;
use Hyperf\HttpServer\Contract\ResponseInterface as HttpResponse;
use Psr\Container\ContainerInterface;
use Psr\Http\Message\ResponseInterface;
use Psr\Http\Message\ServerRequestInterface;
use Psr\Http\Server\MiddlewareInterface;
use Psr\Http\Server\RequestHandlerInterface;
use Hyperf\Utils\Context;

class CorsMiddleware implements MiddlewareInterface
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var RequestInterface
     */
    protected $request;

    /**
     * @var HttpResponse
     */
    protected $response;

    public function __construct(ContainerInterface $container, HttpResponse $response, RequestInterface $request)
    {
        $this->container = $container;
        $this->response = $response;
        $this->request = $request;
    }

    public function process(ServerRequestInterface $request, RequestHandlerInterface $handler): ResponseInterface
    {
        $response = Context::get(ResponseInterface::class);
        $origin = (empty($request->getHeader('Origin')[0]) || $request->getHeader('Origin')[0]== 'null' )
            ? '*'
            :$request->getHeader('Origin')[0];

        $response = $response->withHeader('Access-Control-Allow-Origin',$origin)
            ->withHeader('Access-Control-Allow-Credentials','true')
            ->withHeader('Access-Control-Allow-Methods','GET,POST,PUT,DELETE,PATCH,OPTIONS')
            ->withHeader('Access-Control-Allow-Headers','Authorization, User-Agent, Keep-Alive, Content-Type, x-csrf-token, token, X-Requested-With');
        Context::set(ResponseInterface::class,$response);

        if($request->getMethod() == 'OPTIONS'){
            return $response;
        }

        return $handler->handle($request);
    }
}
